package com.study.talk.module.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study.talk.common.exception.BadRequestException;
import com.study.talk.common.resullt.FwResult;
import com.study.talk.common.util.SecurityUtil;
import com.study.talk.module.entity.User;
import com.study.talk.module.entity.UserInfo;
import com.study.talk.module.service.UserInfoService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author thor
 * @since 2023-12-18
 */
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    @ApiOperation("用户信息")
    @GetMapping("/get")
    public FwResult<UserInfo> getUserInfo() {
        User user = SecurityUtil.getUser();
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        UserInfo body = userInfoService.getOne(wrapper);
        return FwResult.ok(body, "操作成功");
    }


    @ApiOperation("修改用户信息")
    @PutMapping("/update")
    public FwResult<UserInfo> updateUserInfo(@RequestBody UserInfo userInfo) {
        User user = SecurityUtil.getUser();
        if (!user.getId().equals(userInfo.getId())) {
            throw new BadRequestException(401, "不可操作他人账号信息");
        }
        userInfoService.updateById(userInfo);
        return FwResult.ok(userInfo);
    }

    @ApiOperation("修改用户信息")
    @PutMapping("/update/set/info")
    public FwResult<UserInfo> setUserInfo(@RequestBody UserInfo userInfo) {
        userInfoService.updateById(userInfo);
        return FwResult.ok(userInfo);
    }


    @ApiOperation("根据用户id查询用户信息")
    @GetMapping("get/{id}")
    public FwResult<UserInfo> getUserInfoById(@PathVariable("id") Integer id) {
        UserInfo userInfo = userInfoService.getById(id);
        if (null == userInfo) throw new BadRequestException(404, "用户不存在");
        else return FwResult.ok(userInfo, "查询成功");
    }

    @ApiOperation("根据用户名模糊匹配用户")
    @GetMapping("/get/list/{username}")
    public FwResult<List<UserInfo>> getUserInfoList(@PathVariable("username") String username) {
        return FwResult.ok(userInfoService.getUserInfoListByUsername(username));
    }

}
